import 'dart:io';

import 'package:flutter/services.dart';
import 'package:flutter_image_compress/flutter_image_compress.dart';
import 'package:flutter_smart_dialog/flutter_smart_dialog.dart';
import 'package:get/get.dart';
import 'package:image_picker/image_picker.dart';
import 'package:mtf/app/base/BaseController.dart';
import 'package:mtf/app/net/HttpManger.dart';
import 'package:path_provider/path_provider.dart' as path_provider;
import 'package:mtf/app/routes/app_pages.dart';
import 'dart:convert';
/**
 * GetX Template Generator - fb.com/htngu.99
 * */

class uploadVoucherController extends BaseController{
  var rechargeMoney = Get.arguments["money"];
  var preMoney = Get.arguments["amount"];
  var _selectIndex =0.obs;
  set selectIndexObs(value) => _selectIndex.value = value;
  get selectIndexObs => _selectIndex.value;
  var imageArray=[].obs;
  var showBank = true.obs;
  var showWx = false.obs;
  var showAlipay = false.obs;
  var bankName="".obs;
  var bankNum="".obs;
  var bankAddress="".obs;
  var choiceBankName="请选择充值的银行卡".obs;
  var choiceBankId="";
  var wxUrl="".obs;
  var alipayUrl="".obs;


  final _picker = ImagePicker();

  Future<void> selectImage() async {
    final pickedFile = await _picker.pickImage(source: ImageSource.gallery);
    if (pickedFile != null) {
      // 处理所选照片
      reqFileUpload(File(pickedFile.path));
    }
  }

  void reqFileUpload(File file) async {
    print('reqFileUpload${file.path}');
    showLoading();
    var newFile = await compressAndGetFile(file);
    print('newFile${newFile.path}');
    var fileResp = await HttpManager.reqFileUpLoad(newFile);
    if (fileResp.isSuccess() && fileResp.data != null) {
      imageArray.add(fileResp.data?.fileNameUrl);
    }
    hideLoading();
  }

  /// 图片压缩 File -> File
  Future<File> compressAndGetFile(File file) async {
    final dir = await path_provider.getTemporaryDirectory();
    await dir.create(recursive: true);
    final targetPath =
        dir.absolute.path + '/${DateTime.now().microsecondsSinceEpoch}.jpg';
    var result = await FlutterImageCompress.compressAndGetFile(
      file.path,
      targetPath,
      quality: 88,
      rotate: 0,
    );
    return File(result!.path);
  }

  File createFile(String path) {
    final file = File(path);
    if (!file.existsSync()) {
      file.createSync(recursive: true);
    }
    return file;
  }

  @override
  void onInit() {
    super.onInit();
    rechargeConfig();
  }

  void rechargeConfig() async{
    showLoading();
    var resp=await HttpManager.rechargeConfig();
    var userResp=await HttpManager.reqUserInfo();
    if(userResp.isSuccessData()){
      if((userResp.data!.rechargeSuccessNum ??0)<1){
        //首充
        showAlipay.value=false;
        showWx.value=false;
      }
      print('rechargeConfig ${resp.toJson()}');
      if(resp.isSuccessData()){
        if((userResp.data!.rechargeSuccessNum ??0)>0){
          if(resp.data!.weixin!=null&&!(resp.data!.weixin!.payImg!.isEmpty)){
            showWx.value=true;
            wxUrl.value=resp.data!.weixin!.payImg!;
          }
          if(resp.data!.alipay!=null&&!(resp.data!.alipay!.payImg!.isEmpty)){
            showAlipay.value=true;
            alipayUrl.value=resp.data!.alipay!.payImg!;
          }
        }
        bankNum.value=resp.data!.bank?.bankAccount??"";
        bankAddress.value=resp.data!.bank?.bankName??"";
        bankName.value=resp.data!.bank?.bankPayName??"";

      }
    }
    hideLoading();
  }

  void clickBankManager() async{
    var bank=await Get.toNamed(Routes.BANK_MANAGER,arguments: {"choice":true});
    choiceBankName.value=bank["bankName"];
    choiceBankId=bank["bId"];
  }

  void copy(String value){
    Clipboard.setData(ClipboardData(text: value));
    SmartDialog.showNotify(msg: "复制成功", notifyType: NotifyType.success);
  }

  void reqRecharge() async{
    if(imageArray.length==0){
      SmartDialog.showToast("请上传打款截图");
    }else{
      showLoading();
      var imageJson= json.encode(imageArray);
      var typeArray=["bank","weixin","alipay"];
      print('choiceBankId${choiceBankId} preMoney${preMoney}');
      var resp=await HttpManager.recharge(preMoney, imageJson, typeArray[selectIndexObs],user_bank_id: selectIndexObs==0 ? choiceBankId:"");
      if(resp.isSuccess()){
        Get.offNamed(Routes.SUCCESS,arguments: {"title":"充值提交成功","desc":"等待平台审核，请耐心等候","type":1,"buttonText":"返回"});
      }
      hideLoading();
    }

  }
}
